package com.draven.mall.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.draven.mall.entity.Order;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * 订单Mapper接口
 */
@Mapper
public interface OrderMapper extends BaseMapper<Order> {

    /**
     * 查询待接单的订单列表
     * @param page 分页参数
     * @return 分页列表
     */
    @Select("SELECT o.*, m.shop_name as merchant_name, u.username as user_name " +
            "FROM tb_order o " +
            "LEFT JOIN tb_merchant m ON o.merchant_id = m.id " +
            "LEFT JOIN tb_user u ON o.user_id = u.id " +
            "WHERE o.status = 1 " +
            "ORDER BY o.created_time DESC")
    IPage<Order> selectAvailableOrders(Page<Order> page);
    
    /**
     * 查询骑手的配送中订单
     * @param page 分页参数
     * @param riderId 骑手ID
     * @return 分页列表
     */
    @Select("SELECT o.*, m.shop_name as merchant_name, u.username as user_name " +
            "FROM tb_order o " +
            "LEFT JOIN tb_merchant m ON o.merchant_id = m.id " +
            "LEFT JOIN tb_user u ON o.user_id = u.id " +
            "WHERE o.rider_id = #{riderId} AND o.status = 2 " +
            "ORDER BY o.created_time DESC")
    IPage<Order> selectInProgressOrders(Page<Order> page, @Param("riderId") Long riderId);
    
    /**
     * 查询骑手的已完成订单
     * @param page 分页参数
     * @param riderId 骑手ID
     * @return 分页列表
     */
    @Select("SELECT o.*, m.shop_name as merchant_name, u.username as user_name " +
            "FROM tb_order o " +
            "LEFT JOIN tb_merchant m ON o.merchant_id = m.id " +
            "LEFT JOIN tb_user u ON o.user_id = u.id " +
            "WHERE o.rider_id = #{riderId} AND o.status = 3 " +
            "ORDER BY o.created_time DESC")
    IPage<Order> selectCompletedOrders(Page<Order> page, @Param("riderId") Long riderId);
    
    /**
     * 执行自定义SQL查询，返回Long类型结果
     */
    @Select("${sql}")
    Long executeCountSql(@Param("sql") String sql);
    
    /**
     * 执行自定义SQL查询，返回Map列表
     */
    @Select("${sql}")
    List<Map<String, Object>> executeSql(@Param("sql") String sql);

    /**
     * 查询商家信息
     */
    @Select("SELECT id, name, address, phone FROM tb_merchant WHERE id = #{merchantId}")
    Map<String, Object> selectMerchantById(@Param("merchantId") Long merchantId);
} 